package com.dries.portal.app.controller;

import cn.hutool.core.util.StrUtil;
import com.dries.portal.app.vo.User;
import com.dries.security.app.social.AppSingUpUtils;
import com.dries.security.common.api.CommonResult;
import com.dries.security.core.properties.SecurityCoreProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/16 15:27
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private AppSingUpUtils appSingUpUtils;
    @Resource
    private SecurityCoreProperties coreProperties;

    @GetMapping("/me")
    public CommonResult getCurrentUser(HttpServletRequest request, Authentication user) throws UnsupportedEncodingException {

        String header = request.getHeader("Authorization");
        String token = StrUtil.subAfter(header, "bearer", false);

        Claims claims = Jwts.parser()
                .setSigningKey(coreProperties.getOauth2().getJwtSignInKey().getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token).getBody();


        String company = (String) claims.get("company");

        log.info("TOKEN 内容：==================>" + company);


        return CommonResult.success(user);

    }

    @PostMapping("/register")
    public void register(HttpServletRequest request, User user) {

        // 不管是注册用户还是绑定用户，都会拿到一个用户唯一标识
        String userId = user.getUsername();
        // providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
        appSingUpUtils.doPostSignUp(new ServletWebRequest(request), userId);
    }

}
